package com.ktgj.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.DepositType;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.common.CardConstant;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.CalculationRemotelyDTO;
import com.ktgj.customer.domain.dto.CardCRMAllDTO;
import com.ktgj.customer.domain.dto.DiscountDescDTO;
import com.ktgj.customer.domain.dto.PayTypeDTO;
import com.ktgj.customer.domain.vo.DepositInfo;
import com.ktgj.customer.domain.vo.InsuranceReturnVo;
import com.ktgj.customer.domain.vo.ProductVo;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class CardCRMPurchaseServiceImpl implements ICardCRMPurchaseService {

    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private BusinessOrderMapper businessOrderMapper;
    @Autowired
    private BusinessOrderSubMapper businessOrderSubMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IPointRecordService pointRecordService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private IBusinessOrderService businessOrderService;
    @Autowired
    private RemotePayService remotePayService;
    @Autowired
    private IDepositBusinessService depositBusinessService;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private ICardPurchaseService cardOrderResult;
    @Autowired
    private CustomerCardMapper customerCardMapper;
    @Autowired
    private BusinessOrderAssistMapper businessOrderAssistMapper;
    @Autowired
    private IAssistProductService assistProductService;
    @Autowired
    private IInsuranceRecordService insuranceRecordService;
    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;
    @Autowired
    private EmployeeVipresourceMapper employeeVipresourceMapper;

    @Override
    public Map<String, Object> queryPurchaseCardData() {
        Map<String, Object> map = new HashMap<>();

        List<CardCRMAllDTO> cardCRMAllDTOS = cardMapper.selectCRMCardAll();
        map.put("cardList", cardCRMAllDTOS);

        List<PayTypeDTO> payTypeDTOS = cardMapper.getPayType();
        map.put("payTypeList", payTypeDTOS);

        return map;
    }

    @Override
    public CalculationRemotelyDTO calculationRemotely(Long cardId, String years, Long creditsNum, BigDecimal usedDeposit, Long couponId) {
        CalculationRemotelyDTO calculationRemotelyDTO = new CalculationRemotelyDTO();
        Card card = cardMapper.selectCardById(cardId);
        BigDecimal money = null;
        if (years.equals("one"))
            money = card.getPrice();
        else
            money = card.getContinuousPrice().multiply(new BigDecimal(2));

        calculationRemotelyDTO.setCouponMoney(new BigDecimal(0));
        if (couponId != null && couponId != 0) {
            CouponBO coupon = couponService.couponByCustomerRightDetailId(couponId);
            if (coupon != null) {
                DiscountDescDTO discountDescDTO = new DiscountDescDTO();
                switch (coupon.getCouponType()) {
                    case "CouponTypeFullMinus":
                        if (money.compareTo(coupon.getCouponMaxprice()) == -1)
                            break;
                    case "CouponTypeCashCoupon":
                        calculationRemotelyDTO.setCouponMoney(coupon.getCouponPrice());
                        money = money.subtract(coupon.getCouponPrice());
                        break;
                    case "CouponTypeDiscount":
                        BigDecimal dec = money.multiply(coupon.getCouponDiscount());
                        calculationRemotelyDTO.setCouponMoney(dec);
                        money = money.subtract(dec);
                        break;
                }
            }
        }

        calculationRemotelyDTO.setCreditsNumMoney(new BigDecimal(0));
        if (creditsNum != null && creditsNum != 0) {
            Integer dec = creditsNum.intValue() / CardConstant.EXCHANGE;
            BigDecimal decimal = new BigDecimal(dec);
            calculationRemotelyDTO.setCreditsNumMoney(decimal);
            money = money.subtract(decimal);
        }

        calculationRemotelyDTO.setUsedDepositMoney(new BigDecimal(0));
        if (usedDeposit != null && usedDeposit.compareTo(new BigDecimal(0)) == 1) {
            calculationRemotelyDTO.setUsedDepositMoney(usedDeposit);
            money = money.subtract(usedDeposit);
        }

        calculationRemotelyDTO.setUsedMoney(money);

        return calculationRemotelyDTO;
    }

    @Override
    public String buyCardOrder(Long customerId, Long cardId, Long creditsNum, Long couponId, BigDecimal usedMoney, BigDecimal couponMoney, String years, Long customerId1, Long employeeId, Long deptId, CommonReimbursements commonReimbursements, String type, List<Integer> product) throws Exception
    {
//        int count = businessOrderSubMapper.queryCardCount(customerId1, cardId);
//        if (count > 1)
//            return "该卡购买数量已达上限，暂且不能购买，请等待已有的卡片到期再次购买";

        boolean flag = false;
        List<CustomerCard> customerCards = customerCardMapper.customerCards(customerId, cardId);
        if (customerCards != null && customerCards.size() > 0)
        {
            flag = true;
        }

        Card card = cardMapper.selectCardById(cardId);//获取到卡的信息
        String orderSourceDesc = "购买“" + card.getCardSectionName() + "”";
        String orderType = CustomerConstants.newCard.getValue();

        Date date = DateUtils.getNowDate();

        //生成订单
        BusinessOrder businessOrder = new BusinessOrder();
        businessOrder.setPrice(card.getPrice());//支付金额
        businessOrder.setBusinessType(orderType);//业务类型
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        businessOrder.setOrdernum(String.valueOf(snowflakeUtils.nextId()));//订单号
        businessOrder.setState(CustomerConstants.waitPay.getValue());//支付状态
        //businessOrder.setUsedMoney(usedMoney);//实收金额
        businessOrder.setUsedMoney(new BigDecimal(0.1));//实收金额 TODO 测试写死
        businessOrder.setCustomerId(customerId);//会员编号
        businessOrder.setCreateTime(date);//创建时间
        businessOrder.setCreateDemployeeId(employeeId);//创建员工
        businessOrder.setEmployeeId(employeeId);//业绩归属员工id
        businessOrder.setEmployeeDeptid(deptId);//业绩归属员工部门id
        businessOrder.setOrderState(CustomerConstants.waitPay.getValue());//订单状态
        businessOrder.setSourceway(2L);

        businessOrder.setUsedCredits(new BigDecimal(creditsNum / CardConstant.EXCHANGE));//积分抵现

        if (couponId != null)
        {
            businessOrder.setUsedCouponId(couponId);//用户的抵扣卷id
        }
        if (couponMoney != null)
        {
            businessOrder.setUsedCoupon(couponMoney);//抵扣卷抵扣金额
        }
//        businessOrder.setUsedDeposit(usedDeposit);//预留款金额

        businessOrder.setInvoiceTitle(commonReimbursements.getInvoiceHeadsUp());//发票抬头
        businessOrder.setInvoiceTitletype(commonReimbursements.getInvoiceType());//发票类型
        businessOrder.setTaxpayerNum(commonReimbursements.getIdentificationNumber());//收纳人识别码
        businessOrder.setInvoiceAddresss(commonReimbursements.getRegisteredAddress());//开票地址
        businessOrder.setInvoicePhone(commonReimbursements.getPhone());//开票电话
        businessOrder.setInvoiceBankName(commonReimbursements.getBankName());//开票开户行
        businessOrder.setInvoiceCreditCard(commonReimbursements.getBankAccount());//开票银行账号
        if (years.equals("tow"))
        {
            businessOrder.setYears(CustomerConstants.twoYear.getValue());
        }else
        {
            businessOrder.setYears(CustomerConstants.oneYear.getValue());
        }
        Customer customer = customerService.selectCustomerById(customerId);
        if (customer!=null)
        {
            Long id = employeeVipresourceMapper.checkCustomerIdExist(customerId);
            if (id == null)
            {
                EmployeeVipresource employeeVipresource = new EmployeeVipresource();
                employeeVipresource.setCustomerId(customer.getCustomerId());
                employeeVipresource.setEmployeeId(employeeId);
                employeeVipresource.setCustomerPhone(customer.getContractPhoneOne());
                employeeVipresource.setCustomerName(customer.getCustomerName());
                employeeVipresource.setCreattime(new Date());
                employeeVipresource.setDistributeTime(new Date());
                employeeVipresource.setRegiesttime(customer.getCreateTime());
                employeeVipresourceMapper.insertEmployeeVipresource(employeeVipresource);
            }
        }
        businessOrderMapper.insertBusinessOrder(businessOrder);

        if (product.size() > 0) {
            for (Integer integer : product) {
                AssistProduct assistProduct = assistProductService.queryAssistProduct(Long.valueOf(integer));
                BusinessOrderAssist businessOrderAssist = new BusinessOrderAssist();
                businessOrderAssist.setName(assistProduct.getName());
                businessOrderAssist.setPrice(assistProduct.getSalePrice());
                businessOrderAssist.setAssistProductId(Long.valueOf(integer));
                businessOrderAssist.setStatus("wait");
                businessOrderAssist.setCreateTime(new Date());
                businessOrderAssist.setOrdernum(businessOrder.getOrdernum());
                businessOrderAssist.setInsType(assistProduct.getProductType());
                businessOrderAssistMapper.insertBusinessOrderAssist(businessOrderAssist);
            }
        }

        //生成子订单
        BusinessOrderSub businessOrderSub = new BusinessOrderSub();
        businessOrderSub.setOrderNum(String.valueOf(snowflakeUtils.nextId()));//订单号
        businessOrderSub.setOrderId(businessOrder.getOrderId());//订单主表id
        businessOrderSub.setCardId(cardId);//卡id
        businessOrderSub.setCardName(card.getCardSectionName());//卡名称
        businessOrderSub.setCardPrice(years.equals("one") ? card.getPrice() : card.getContinuousPrice());//卡售价
        if (type.equals(EmHelper.customerCardType.Immediately.getValue()))
        {//立刻开卡
            businessOrderSub.setRenewCardStatus(CustomerConstants.newCard.getValue());//开卡续费状态
        } else if (type.equals(EmHelper.customerCardType.AfterExpiration.getValue()))
        {//过期后开卡
            businessOrderSub.setRenewCardStatus(CustomerConstants.newContinuousCard.getValue());//开卡续费状态
        }

        businessOrderSub.setSame(String.valueOf(flag));

        businessOrderSub.setNewCustomerid(customerId1);//卡归属人会员编号
        businessOrderSub.setMyselfBuycard(customerId.equals(customerId1) ? 0L : 1L);//是否本人购卡
        businessOrderSubMapper.insertBusinessOrderSub(businessOrderSub);

        List<BusinessOrderSub> list = new ArrayList<>();
        list.add(businessOrderSub);

        if (years.equals("tow"))
        {//如果是连续包年购卡，需要一次买两年，生成两笔子订单
            BusinessOrderSub businessOrderSubTwo = new BusinessOrderSub();
            businessOrderSubTwo.setOrderNum(String.valueOf(snowflakeUtils.nextId()));//订单号
            businessOrderSubTwo.setOrderId(businessOrder.getOrderId());//订单主表id
            businessOrderSubTwo.setCardId(cardId);//卡id
            businessOrderSubTwo.setCardName(card.getCardSectionName());//卡名称
            businessOrderSubTwo.setCardPrice(card.getContinuousPrice());//卡售价
            businessOrderSubTwo.setRenewCardStatus(CustomerConstants.newContinuousCard.getValue());//开卡续费状态
            businessOrderSubTwo.setNewCustomerid(customerId1);//卡归属人会员编号
            businessOrderSubTwo.setMyselfBuycard(customerId.equals(customerId1) ? 0L : 1L);//是否本人购卡
            businessOrderSubMapper.insertBusinessOrderSub(businessOrderSubTwo);
            list.add(businessOrderSubTwo);
        }

        businessOrder.setBusinessOrderSubs(list);

        try
        {
            pointRecordService.spend(customerId, creditsNum, orderType, businessOrder.getOrderId(), orderSourceDesc, couponId, 1L);//会员id、要扣减的积分、订单类型、订单id、订单描述（客户端展示使用），例如机票 显示航程+航班号、使用优惠卷的id、预留款、操作员工id
        } catch (Exception e)
        {
            throw new Exception(e.getMessage());
        }

        if (customerId != null && customerId != 0l)
        {
            //会员消息

            CustomerMessage customerMessage = new CustomerMessage();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            String orderDate = sdf.format(businessOrder.getCreateTime());
            //从哪获取订单信息

            String star = "您在" + orderDate + orderSourceDesc + "请在规定时间内支付";
            customerMessage.setMessageContent(star);
            //订单类型
            customerMessage.setBusinessType(BusinessTypeConstants.customer.getValue());
            customerMessage.setCustomerId(customerId);
            customerMessage.setBusinessOrderId(new Long(businessOrder.getOrdernum()));
            customerService.addCustomerMessage(customerMessage);
        }
        //存入redis，查找待支付订单时用
        redisService.setCacheObject("order" + customerId + "u" + businessOrder.getOrdernum(), JSON.toJSONString(businessOrder), 60 * 30l, TimeUnit.SECONDS);//存入redis,有效期30分钟
        return businessOrder.getOrdernum();
    }

    /**
     * CRM购卡银联二维码支付
     * */
    @Override
    public UnionPayQRCodeResponseApi cardCRMPurchaseGetQRCode(String orderNum, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        Employee loginEmployee = loginService.getLoginEmployee(request);
        if (loginEmployee == null){
            throw new Exception("登录已过期");
        }

        BusinessOrder businessOrder = businessOrderService.selectBusinessOrderByOrdernum(orderNum);
        if (amount.compareTo(new BigDecimal(0)) > 0){
            businessOrder.setUsedMoney(businessOrder.getUsedMoney().subtract(amount));
            businessOrder.setUpdateTime(new Date());
            businessOrder.setAmount(amount);
            int i = businessOrderService.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            /*DepositBusiness depositBusiness = new DepositBusiness();
            depositBusiness.setRemark("购卡银联二维码支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.Customer.getValue());
            depositBusiness.setOperatorId(loginEmployee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(businessOrder.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderNum));
            depositBusiness.setDrawState("false");
            Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            boolean audit = depositBusinessService.goldCoinAudit(loginEmployee.getEmployeeId(), aLong, "购卡银联二维码支付");
            if (!audit){
                throw new Exception("审核失败,请进行人工审核");
            }*/
        }

        String cardCode = "";
        if (businessOrder.getUsedMoney().compareTo(new BigDecimal(0)) == 0){
            Long billNo = System.currentTimeMillis() / 1000;
            cardCode = cardOrderResult.cardOrderResult(true, businessOrder.getOrdernum(), billNo.toString(), BusinessTypeConstants.UnionQRCodePay.getValue());

            UnionPayQRCodeResponseApi unionPayQRCodeResponseApi = new UnionPayQRCodeResponseApi();
            unionPayQRCodeResponseApi.setErrMsg("支付成功");
            unionPayQRCodeResponseApi.setErrCode("200");

            businessOrder.setCardCode(cardCode);
            List<BusinessOrderAssist> orderAssists = businessOrderAssistMapper.queryBusinessOrderAssistByOrderNum(businessOrder.getOrdernum());
            if (orderAssists != null && orderAssists.size() > 0)
                businessOrderAssist(businessOrder, orderAssists);
            businessOrder.setPayType(BusinessTypeConstants.Reserve_Money.getValue());
            businessOrder.setState(CustomerConstants.payd.getValue());
            businessOrder.setOrderState(CustomerConstants.payd.getValue());

            DepositInfo depositInfo = new DepositInfo();
            depositInfo.setDepositCount(businessOrder.getAmount());
            depositInfo.setCustomerId(businessOrder.getCustomerId());
            depositInfo.setDepositType(DepositType.deposit);
            boolean deposit = depositBusinessService.spendDeposit(depositInfo);
            if (!deposit)
                throw new Exception("花费预留款失败");

            int i = businessOrderMapper.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单状态失败");
            }
            return unionPayQRCodeResponseApi;
        }

        Map<String, String> param = new HashMap<>();
        param.put("billNo", "5676" + businessOrder.getOrdernum());
        param.put("totalAmount", businessOrder.getUsedMoney().multiply(new BigDecimal(100)).longValue() + "");
        param.put("notifyUrl", "http://106.38.39.137:8080/customer/callback/unionPayQRCodeCallback");
        UnionPayQRCodeResponseApi unionPayQRCodeResponseApi = remotePayService.getQRCode(param);
        int i = businessOrderService.updateBillQRCode(businessOrder.getOrdernum(), unionPayQRCodeResponseApi.getBillQRCode());
        if (i > 0){
            return unionPayQRCodeResponseApi;
        }
        else {
            throw new Exception("支付信息保存失败，请联系管理员，并重新下单");
        }
    }

    /**
     * CRM购卡电话语音支付
     * */
    @Override
    public String cardCRMPurchaseVoicePay(String orderNum, String cardNumber, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        Employee loginEmployee = loginService.getLoginEmployee(request);
        if (loginEmployee == null){
            throw new Exception("登录已过期");
        }

        BusinessOrder businessOrder = businessOrderService.selectBusinessOrderByOrdernum(orderNum);
        Customer customer = customerService.selectCustomerById(businessOrder.getCustomerId());
        if (amount.compareTo(new BigDecimal(0)) > 0){
            businessOrder.setUsedMoney(businessOrder.getUsedMoney().subtract(amount));
            businessOrder.setUpdateTime(new Date());
            businessOrder.setAmount(amount);
            int i = businessOrderService.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            /*DepositBusiness depositBusiness = new DepositBusiness();
            depositBusiness.setRemark("购卡电话语音支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.Customer.getValue());
            depositBusiness.setOperatorId(loginEmployee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(businessOrder.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderNum));
            depositBusiness.setDrawState("false");
            Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            boolean coinAudit = depositBusinessService.goldCoinAudit(loginEmployee.getEmployeeId(), aLong, "购卡电话语音支付");
            if (!coinAudit){
                throw new Exception("审核失败，请进行人工审核");
            }*/
        }

        if (businessOrder.getUsedMoney().compareTo(new BigDecimal(0)) == 0){
            SnowFlake snowFlake = new SnowFlake(29, 29);
            Long billNo = snowFlake.nextId();
            String cardCode = cardOrderResult.cardOrderResult(true, businessOrder.getOrdernum(), billNo.toString(), BusinessTypeConstants.BankCredit.getValue());
            businessOrder.setCardCode(cardCode);
            List<BusinessOrderAssist> orderAssists = businessOrderAssistMapper.queryBusinessOrderAssistByOrderNum(businessOrder.getOrdernum());
            if (orderAssists != null && orderAssists.size() > 0)
                businessOrderAssist(businessOrder, orderAssists);
            businessOrder.setPayType(BusinessTypeConstants.Reserve_Money.getValue());
            businessOrder.setState(CustomerConstants.payd.getValue());
            businessOrder.setOrderState(CustomerConstants.payd.getValue());

            DepositInfo depositInfo = new DepositInfo();
            depositInfo.setDepositCount(businessOrder.getAmount());
            depositInfo.setCustomerId(businessOrder.getCustomerId());
            depositInfo.setDepositType(DepositType.deposit);
            boolean deposit = depositBusinessService.spendDeposit(depositInfo);
            if (!deposit)
                throw new Exception("花费预留款失败");

            int i = businessOrderMapper.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单状态失败");
            }
            return "支付成功";
        }

        Map<String, Object> voice = new HashMap<>();
        voice.put("mobileNumber", customer.getContractPhoneOne());
        voice.put("bankCardNo", cardNumber);
        voice.put("idCardNo", customer.getCustCertificateNo());
        voice.put("idCardName", customer.getCustomerName());
        voice.put("orderAmount", businessOrder.getUsedMoney().multiply(new BigDecimal(100)));
        voice.put("orderId", businessOrder.getOrdernum());
        voice.put("asynAddress", "http://106.38.39.137:8080/customer/callback/cardVoicePayCallback");

        String pay = remotePayService.voicePay(voice);

        if (!pay.equals("请注意来电")){
            businessOrder.setMsg(pay + ":语音支付失败");
            int i = businessOrderMapper.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("添加语音支付错误信息失败");
            }
        }
        return pay;
    }

    /**
     * CRM购卡无卡无密支付
     * */
    @Override
    public String cardCRMPurchaseBankCard(String orderNum, Long bankCardId, HttpServletRequest request, BigDecimal amount, String type) throws Exception {
        Employee loginEmployee = loginService.getLoginEmployee(request);
        if (loginEmployee == null){
            throw new Exception("登录已过期");
        }

        BusinessOrder businessOrder = businessOrderService.selectBusinessOrderByOrdernum(orderNum);
        if (amount.compareTo(new BigDecimal(0)) > 0){
            businessOrder.setUsedMoney(businessOrder.getUsedMoney().subtract(amount));
            businessOrder.setUpdateTime(new Date());
            businessOrder.setAmount(amount);
            int i = businessOrderMapper.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            /*DepositBusiness depositBusiness = new DepositBusiness();
            depositBusiness.setRemark("购卡无卡无密支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.Customer.getValue());
            depositBusiness.setOperatorId(loginEmployee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(businessOrder.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(Long.valueOf(orderNum));
            depositBusiness.setDrawState("false");
            Long aLong = depositBusinessService.insertDepositBusiness(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            boolean coinAudit = depositBusinessService.goldCoinAudit(loginEmployee.getEmployeeId(), aLong, "购卡无卡无密支付");
            if (!coinAudit){
                throw new Exception("审核失败，请进行人工审核");
            }*/
        }

        if (businessOrder.getUsedMoney().compareTo(new BigDecimal(0)) == 0){
            SnowFlake snowFlake = new SnowFlake(29, 29);
            Long billNo = snowFlake.nextId();
            String cardCode = cardOrderResult.cardOrderResult(true, businessOrder.getOrdernum(), billNo.toString(), BusinessTypeConstants.BankCredit.getValue());
            businessOrder.setCardCode(cardCode);
            List<BusinessOrderAssist> orderAssists = businessOrderAssistMapper.queryBusinessOrderAssistByOrderNum(businessOrder.getOrdernum());
            if (orderAssists != null && orderAssists.size() > 0)
                businessOrderAssist(businessOrder, orderAssists);
            businessOrder.setPayType(BusinessTypeConstants.Reserve_Money.getValue());
            businessOrder.setState(CustomerConstants.payd.getValue());
            businessOrder.setOrderState(CustomerConstants.payd.getValue());

            DepositInfo depositInfo = new DepositInfo();
            depositInfo.setDepositCount(businessOrder.getAmount());
            depositInfo.setCustomerId(businessOrder.getCustomerId());
            depositInfo.setDepositType(DepositType.deposit);
            boolean deposit = depositBusinessService.spendDeposit(depositInfo);
            if (!deposit)
                throw new Exception("花费预留款失败");

            int i = businessOrderMapper.updateBusinessOrder(businessOrder);
            if (i <= 0){
                throw new Exception("修改订单状态失败");
            }
            return "支付成功";
        }

        BankCard bankCard = bankCardService.selectBankCardById(bankCardId);
        BankCardApi bankCardApi = new BankCardApi();
        BeanUtils.copyProperties(bankCard, bankCardApi);

        Customer customer = customerService.selectCustomerById(businessOrder.getCustomerId());
        CustomerApi customerApi = new CustomerApi();
        BeanUtils.copyProperties(customer, customerApi);

        BankPayInfoApi bankPayInfo = new BankPayInfoApi();
        bankPayInfo.setJsjOrderId(businessOrder.getOrdernum());
        bankPayInfo.setMoneyAmout(businessOrder.getUsedMoney().toString());
        bankPayInfo.setCustomer(customerApi);
        bankPayInfo.setCard(bankCardApi);


        YeeBaoResultApi yeeBaoResultApi;

        String bankCardType = bankCard.getCardType();
        if (bankCardType.equals("creditcard")) {//信用卡
            bankPayInfo.setPayType("Crm");
            yeeBaoResultApi = remotePayService.CreditSale(bankPayInfo);
        } else {//借记卡
            yeeBaoResultApi = remotePayService.DebitSale(bankPayInfo);
        }

        String cardCode = "";
        if (yeeBaoResultApi.getCode() != null && !yeeBaoResultApi.getCode().equals("") && yeeBaoResultApi.getCode().equals("1")) {
            if (bankCardType.equals("creditcard")) {
                businessOrder.setPayType(BusinessTypeConstants.BankCredit.getValue());
                cardCode = cardOrderResult.cardOrderResult(true, businessOrder.getOrdernum(), yeeBaoResultApi.getTrxId(), BusinessTypeConstants.BankCredit.getValue());
            } else {
                businessOrder.setPayType(BusinessTypeConstants.BankDebit.getValue());
                cardCode = cardOrderResult.cardOrderResult(true, businessOrder.getOrdernum(), yeeBaoResultApi.getTrxId(), BusinessTypeConstants.BankDebit.getValue());
            }
            businessOrder.setState(CustomerConstants.payd.getValue());
            businessOrder.setOrderState(CustomerConstants.payd.getValue());
            businessOrder.setPartyPayNum(yeeBaoResultApi.getTrxId());
            businessOrder.setCreditCard(bankCardApi.getCardNumber());
            businessOrderMapper.updateBusinessOrder(businessOrder);
            businessOrder.setCardCode(cardCode);
            List<BusinessOrderAssist> orderAssists = businessOrderAssistMapper.queryBusinessOrderAssistByOrderNum(businessOrder.getOrdernum());
            if (orderAssists != null && orderAssists.size() > 0)
                businessOrderAssist(businessOrder, orderAssists);
            return "支付成功";
        } else {
            return yeeBaoResultApi.getErrorMsg();
        }
    }

    private void businessOrderAssist(BusinessOrder businessOrder, List<BusinessOrderAssist> businessOrderAssists) {
        for (BusinessOrderAssist businessOrderAssist : businessOrderAssists) {
            if (businessOrderAssist.getInsType().equals("insurance")) {
                ProductVo productVo = new ProductVo();
                productVo.id = businessOrderAssist.getAssistProductId();
                productVo.cardNum = businessOrder.getCardCode();
                productVo.orderNum = businessOrder.getOrdernum();
                productVo.paymentChannel = businessOrder.getPayType();
                productVo.orderSource = BusinessTypeConstants.customer.getValue();
                try {
                    InsuranceReturnVo insuranceReturnVo = insuranceRecordService.insertInsuranceRecord(businessOrder.getCustomerId(), productVo);
                    if (insuranceReturnVo != null) {
                        if (insuranceReturnVo.isSuccess()) {
                            businessOrderAssist.setStatus("normal");
                            businessOrderAssistMapper.updateBusinessOrderAssist(businessOrderAssist);
                        } else {
                            businessOrderAssist.setStatus("fail");
                            businessOrderAssistMapper.updateBusinessOrderAssist(businessOrderAssist);
                        }
                    } else {
                        businessOrderAssist.setStatus("fail");
                        businessOrderAssistMapper.updateBusinessOrderAssist(businessOrderAssist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (businessOrderAssist.getInsType().equals("conpon")) {
                AssistProduct assistProduct = assistProductService.queryAssistProduct(businessOrderAssist.getAssistProductId());
                Coupon coupon = couponService.couponById(assistProduct.getProductTypeid());
                CustomerRightdetail customerRightdetail = new CustomerRightdetail();
                customerRightdetail.setCustomerId(businessOrder.getCustomerId());
                customerRightdetail.setRightdetailId(coupon.getCouponId());
                customerRightdetail.setRightdetailName(coupon.getCouponName());
                customerRightdetail.setCouponMoney(new BigDecimal(coupon.getCouponPrice()));
                customerRightdetail.setValidDate(new Date());
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(new Date());
                calendar.add(Calendar.YEAR, 1);
                customerRightdetail.setInvalidDate(calendar.getTime());
                customerRightdetail.setCreateEmployeeId(1L);
                customerRightdetail.setCreateTime(new Date());
                customerRightdetail.setRightdetailSource(CustomerConstants.rightSourcePack.getValue());
                customerRightdetail.setRightdetailType(CustomerConstants.rightTypeCoupon.getValue());
                customerRightdetail.setRightdetailTypeid(coupon.getCouponId());
                customerRightdetail.setRightdetailState(CustomerConstants.unexecuted.getValue());
                customerRightdetailMapper.insertCustomerRightdetail(customerRightdetail);
            }
        }
    }
}
